<?php
// 去掉WP版本号
remove_action('wp_head', 'wp_generator');

// 去掉评论内容网址超链
// remove_filter('comment_text', 'make_clickable', 9);

// 去掉系统相册样式
add_filter( 'use_default_gallery_style', '__return_false' );

//修改登录界面
function change_wp_login_logo() {
	echo '<style type="text/css">h1 a { background-image:url('.get_bloginfo('template_directory').'/images/logo-login.gif) !important; padding-bottom: 0 !important; }</style>';
}
function change_wp_login_url( $url ) {
	return get_bloginfo('url');
}
function change_wp_login_title() {
	return get_option('blogname');
}
add_action('login_head', 'change_wp_login_logo');
add_filter('login_headerurl', 'change_wp_login_url');
add_filter('login_headertitle', 'change_wp_login_title');

//自定义默认头像
add_filter( 'avatar_defaults', 'newgravatar' );
function newgravatar ($avatar_defaults) {
	$myavatar = get_bloginfo('template_directory') . '/images/avatar.gif';
	$avatar_defaults[$myavatar] = "无头像";
	return $avatar_defaults;
}

//相册幻灯片 
add_filter('the_content', 'colorbox_gall_replace', 99);
function colorbox_gall_replace ($content){
	global $post;
	$pattern = "/<a(.*?)href=('|\")([^>]*).(bmp|gif|jpeg|jpg|png)('|\")(.*?)>(.*?)<\/a>/i";
	$replacement = '<a$1href=$2$3.$4$5$6 rel="cboxElement">$7</a>';
	$content = preg_replace($pattern, $replacement, $content);
	return $content;
}

// 缩略图
if ( function_exists('add_theme_support')){
	add_theme_support('post-thumbnails');
	set_post_thumbnail_size( 500, 300, true );
	add_image_size( 'focus-thumb', 500, 300, true );
}

/**
 * 名称：文章目录插件
 * 作者：露兜
 * 博客：http://www.ludou.org/
 * 最后修改：2011年2月10日
 */
function article_index($content) {

	$matches = array();
	$ul_li = '';

	$r = "/<h3>([^<]+)<\/h3>/im";

	if(preg_match_all($r, $content, $matches)) {
		foreach($matches[1] as $num => $title) {
			$content = str_replace($matches[0][$num], '<h3 id="title-'.$num.'">'.$title.'</h3>', $content);
			$ul_li .= '<li><a href="#title-'.$num.'" title="'.$title.'">'.$title."</a></li>\n";
		}

		$content = "\n<div id=\"article-index\">
				<strong>目录</strong>
				<ul id=\"index-ul\">\n" . $ul_li . "</ul>
			</div>\n" . $content;
	}

	return $content;
}

add_filter( "the_content", "article_index" );

// 显示主题参数页面
if(is_admin()) require_once ('theme-options.php');
add_theme_support('automatic-feed-links');

// 小工具
if( function_exists('register_sidebar')){
	register_sidebar(array(
		'name' => 'Side1',
		'description' => 'Widgets in this area will be shown on the right-hand side.',
		'before_widget' => '<div class="box">',
		'after_widget' => '</div>',
		'before_title' => '<h2>',
		'after_title' => '</h2>'
	));
}

/* <<小牆>> Anti-Spam v1.83 by Willin Kan.
class anti_spam {
	function anti_spam() {
		if ( !current_user_can('read') ) {
			add_action('template_redirect', array($this, 'w_tb'), 1);
			add_action('init', array($this, 'gate'), 1);
			add_action('preprocess_comment', array($this, 'sink'), 1);
		}
	}
	// 設欄位
	function w_tb() {
		if ( is_singular() ) {
			// 非中文語系
			if ( stripos($_SERVER['HTTP_ACCEPT_LANGUAGE'], 'zh') === false ) {
				add_filter( 'comments_open', create_function('', "return false;") ); // 關閉評論
			} else {
				ob_start(create_function('$input','return preg_replace("#textarea(.*?)name=([\"\'])comment([\"\'])(.+)/textarea>#",
				"textarea$1name=$2wwmm_w$3$4/textarea><textarea name=\"comment\" cols=\"100%\" rows=\"4\" style=\"display:none\"></textarea>",$input);') );
			}
		}
	}
	// 檢查
	function gate() {
		$w = 'wwmm_w';
		if ( !empty($_POST[$w]) && empty($_POST['comment']) ) {
			$_POST['comment'] = $_POST[$w];
		} else {
			$request = $_SERVER['REQUEST_URI'];
			$IP			= $_SERVER['REMOTE_ADDR']; // 可用於屏蔽 IP
			$way		 = isset($_POST[$w]) ? '手動操作' : '未經評論表格';
			$spamcom = isset($_POST['comment']) ? $_POST['comment'] : '';
			$_POST['spam_confirmed'] = "請求: ". $request. "\nIP: ". $IP. "\n方式: ". $way. "\n內容: ". $spamcom. "\n -- 記錄成功 --";
		}
	}
	// 處理
	function sink( $comment ) {
		// 不管 Trackbacks/Pingbacks
		if ( in_array( $comment['comment_type'], array('pingback', 'trackback') ) ) return $comment;

		// 已確定為 spam
		if ( !empty($_POST['spam_confirmed']) ) {
			// 方法一: 直接擋掉, 將 die(); 前面兩斜線刪除即可.
			//die();
			// 方法二: 標記為 spam, 留在資料庫檢查是否誤判.
			add_filter('pre_comment_approved', create_function('', 'return "spam";'));
			$comment['comment_content'] = "[ 小牆判斷這是Spam! ]\n". $_POST['spam_confirmed'];
			$this->add_black( $comment );
		} else {
			// 檢查頭像
			$f = md5( strtolower($comment['comment_author_email']) );
			$g = sprintf( "http://%d.gravatar.com", (hexdec($f{0}) % 2) ) .'/avatar/'. $f .'?d=404';
			$headers = @get_headers( $g );
			if ( !preg_match("|200|", $headers[0]) ) {
				// 沒頭像的列入待審
				add_filter('pre_comment_approved', create_function('', 'return "0";'));
				//$this->add_black( $comment );
				}
		}
		return $comment;
	}
	// 列入黑名單
	function add_black( $comment ) {
		$blacklist = get_option('blacklist_keys');
		update_option('blacklist_keys', $comment['comment_author'] . "\n" . $blacklist);
	}
}
$anti_spam = new anti_spam();
 */
 
// 标题文字截断
function cut_str($src_str,$cut_length){
	$return_str='';
	$i=0;
	$n=0;
	$str_length=strlen($src_str);
	while (($n<$cut_length) && ($i<=$str_length)){
		$tmp_str=substr($src_str,$i,1);
		$ascnum=ord($tmp_str);
		if ($ascnum>=224){
			$return_str=$return_str.substr($src_str,$i,3);
			$i=$i+3;
			$n=$n+2;
		}elseif ($ascnum>=192){
			$return_str=$return_str.substr($src_str,$i,2);
			$i=$i+2;
			$n=$n+2;
		}elseif ($ascnum>=65 && $ascnum<=90){
			$return_str=$return_str.substr($src_str,$i,1);
			$i=$i+1;
			$n=$n+2;
		}else {
			$return_str=$return_str.substr($src_str,$i,1);
			$i=$i+1;
			$n=$n+1;
		}
	}
	if ($i<$str_length){
		$return_str = $return_str . '';
	}
	if (get_post_status() == 'private'){
		$return_str = $return_str . '（private）';
	}
	return $return_str;
}

// 评论贴图
function embed_images($content) {
	$content = preg_replace('/\[img=?\]*(.*?)(\[\/img)?\]/e', '"<img src=\"$1\" alt=\"" . basename("$1") . "\" />"', $content);
	return $content;
}
//add_filter('comment_text', 'embed_images'); 

// 获取当前网页的完整URL
function curPageURL(){
	$pageURL = 'http://';

	$this_page = $_SERVER["REQUEST_URI"]; 
	if (strpos($this_page , "?") !== false) 
		$this_page = reset(explode("?", $this_page));

	$pageURL .= $_SERVER["SERVER_NAME"]  . $this_page;

	return $pageURL;
}

/* Mini Pagenavi v1.0 by Willin Kan. */
if ( !function_exists('pagenavi') ) {
	function pagenavi( $p = 3 ) { // 取当前页前后各 2 页
		if ( is_singular() ) return; // 文章与插页不用
		global $wp_query, $paged;
		$max_page = $wp_query->max_num_pages;
		if ( $max_page == 1 ) return; // 只有一页不用
		if ( empty( $paged ) ) $paged = 1;
		if ( $paged > 1 ) p_link( $paged - 1, '上一页', '« 上一页' );/* 如果当前页大于1就显示上一页链接 */
		if ( $paged > $p + 1 ) p_link( 1, '最前页' );
		if ( $paged > $p + 2 ) echo '... ';
		for( $i = $paged - $p; $i <= $paged + $p; $i++ ) { // 中间页
			if ( $i > 0 && $i <= $max_page ) $i == $paged ? print "<span class='page-numbers current'>{$i}</span> " : p_link( $i );
		}
		if ( $paged < $max_page - $p - 1 ) echo '... ';
		if ( $paged < $max_page - $p ) p_link( $max_page, '最后页' );
		if ( $paged < $max_page ) p_link( $paged + 1,'下一页', '下一页 »' );/* 如果当前页不是最后一页显示下一页链接 */
	}
	function p_link( $i, $title = '', $linktype = '' ) {
		if ( $title == '' ) $title = "第 {$i} 页";
		if ( $linktype == '' ) { $linktext = $i; } else { $linktext = $linktype; }
		echo "<a class='page-numbers' href='", esc_html( get_pagenum_link( $i ) ), "' title='{$title}'>{$linktext}</a> ";
	}
}

// 表情路径
add_filter('smilies_src','custom_smilies_src',1,10);
function custom_smilies_src ($img_src, $img, $siteurl){
	return get_bloginfo('template_directory').'/smilies/'.$img;
}

// 人性化时间
function time_ago( $type = 'commennt', $day = 14 ) {
	$d = $type == 'post' ? 'get_post_time' : 'get_comment_time';
	if (time() - $d('U') > 60*60*24*$day) return;
	echo ' (', human_time_diff($d('U'), strtotime(current_time('mysql', 0))), '前)';
}
function smc_time_since($timestamp) {
	$since = abs(time()-$timestamp); $gmt_offset = get_option('gmt_offset') * 3600;
	$timestamp += $gmt_offset; $current_time = mktime() + $gmt_offset;
	if(floor($since/3600)){
		if(gmdate('Y-m-d',$timestamp) == gmdate('Y-m-d',$current_time)){
			$output = '今天 ';
			$output.= gmdate('H:i',$timestamp);
		}else{
			if(gmdate('Y',$timestamp) == gmdate('Y',$current_time)){
				$output = gmdate('m月d日 H:i',$timestamp);
			}else{
				$output = gmdate('Y年m月d日 H:i',$timestamp);
			}
		}
	}else{
		if(($output=floor($since/60))){
			$output = $output.'分钟前';
		}else $output = '刚刚';
	}
	return $output;
}

// 留言信息
function WelcomeCommentAuthorBack($email = ''){
	if(empty($email)){
		return;
	}
	global $wpdb;

	$past_30days = gmdate('Y-m-d H:i:s',((time()-(24*60*60*30))+(get_option('gmt_offset')*3600)));
	$sql = "SELECT count(comment_author_email) AS times FROM $wpdb->comments
				WHERE comment_approved = '1'
				AND comment_author_email = '$email'
				AND comment_date >= '$past_30days'";
	$times = $wpdb->get_results($sql);
	$times = ($times[0]->times) ? $times[0]->times : 0;
	$message = $times ? sprintf(__('过去30天里，你共评论了<strong>%1$s</strong>次，感谢关注！' ), $times) : '你已很久都没有评论了，这次想说点什么？';

	return $message;
}

// 去掉后台升级提示 Willin Kan
if ( !current_user_can('administrator') ) {
	add_filter('pre_option_update_core',    create_function('$a', "return null;"));
	add_filter('pre_option_update_plugins', create_function('$a', "return null;"));
	add_filter('pre_option_update_themes',  create_function('$a', "return null;"));

	add_filter('pre_transient_update_core',    create_function('$a', "return null;"));
	add_filter('pre_transient_update_plugins', create_function('$a', "return null;"));
	add_filter('pre_transient_update_themes',  create_function('$a', "return null;"));

	add_filter('pre_site_transient_update_core',    create_function('$a', "return null;"));
	add_filter('pre_site_transient_update_plugins', create_function('$a', "return null;"));
	add_filter('pre_site_transient_update_themes',  create_function('$a', "return null;"));

	remove_action('init', 'wp_version_check');
	remove_action('admin_init', '_maybe_update_plugins');
	remove_action('admin_init', '_maybe_update_themes');

	remove_action('admin_init', '_maybe_update_core');
	remove_action('admin_init', '_maybe_update_plugins');
	remove_action('admin_init', '_maybe_update_themes');
	
}

//投稿者和订阅者 隐藏管理工具栏
if ( current_user_can('contributor') || current_user_can('subscriber') ) {
	add_filter('show_admin_bar','__return_false');
}

// 后台权限控制
if ( current_user_can('author') || current_user_can('contributor') ) {	//作者和投稿者
	function custom_user() {
		remove_meta_box('postcustom','post','normal');
		remove_meta_box('trackbacksdiv','post','normal');
		remove_meta_box('commentsdiv','post','normal');
		remove_meta_box('slugdiv','post','normal');

		remove_meta_box('postcustom','page','normal');
		remove_meta_box('trackbacksdiv','page','normal');
		remove_meta_box('commentstatusdiv','page','normal');
		remove_meta_box('commentsdiv','page','normal'); 

		remove_meta_box('subsubsub','page','normal');

		slt_removeMenu( 'edit-comments.php' );
	}
	add_action('admin_init','custom_user'); 
}
if ( current_user_can('contributor') ) {	//投稿者
	function custom_contributor() {
		//remove_meta_box('commentstatusdiv','post','normal');
		remove_meta_box('fastinsert','post','normal');
	}
	add_action('admin_init','custom_contributor'); 
}

// 移除后台主菜单	http://sltaylor.co.uk/blog/customize-wordpress-admin-menus/
function slt_removeMenu( $item ) {
	global $menu;
	foreach ( $menu as $menuKey => $menuItem ) {
		if ( $menuItem[2] == $item ) {
			unset( $menu[$menuKey] );
			break;
		}
	}
}

// 随机函数
function randoms($stat, $end, $num) {
	$t = range($stat, $end);
	shuffle($t);
	return array_slice($t, -$num);
}

/* comment_mail_notify v1.0 by willin kan. (有勾選欄, 由訪客決定) */
function comment_mail_notify($comment_id) {
	$admin_notify = '1'; // admin 要不要收回覆通知 ( '1'=要 ; '0'=不要 )
	$admin_email = get_bloginfo ('admin_email'); // $admin_email 可改為你指定的 e-mail.
	$comment = get_comment($comment_id);
	$comment_author_email = trim($comment->comment_author_email);
	$parent_id = $comment->comment_parent ? $comment->comment_parent : '';
	global $wpdb;
	if ($wpdb->query("Describe {$wpdb->comments} comment_mail_notify") == '')
		$wpdb->query("ALTER TABLE {$wpdb->comments} ADD COLUMN comment_mail_notify TINYINT NOT NULL DEFAULT 0;");
	if (($comment_author_email != $admin_email && isset($_POST['comment_mail_notify'])) || ($comment_author_email == $admin_email && $admin_notify == '1'))
		$wpdb->query("UPDATE {$wpdb->comments} SET comment_mail_notify='1' WHERE comment_ID='$comment_id'");
	$notify = $parent_id ? get_comment($parent_id)->comment_mail_notify : '0';
	$spam_confirmed = $comment->comment_approved;
	if ($parent_id != '' && $spam_confirmed != 'spam' && $notify == '1') {
		$wp_email = 'no-reply@' . preg_replace('#^www\.#', '', strtolower($_SERVER['SERVER_NAME'])); // e-mail 发出点, no-reply 可改为别的 e-mail.
		$to = trim(get_comment($parent_id)->comment_author_email);
		$subject = '[' . get_option('blogname') . '] 您的评论有人回复啦！';
		$message = '
		<div style="color:#100;background-color:#f9f9f9;border:1px solid #EEE;padding:0 10px;">
			<p><strong>' . trim(get_comment($parent_id)->comment_author) . '</strong>，您好！</p>
			<p>有人回复了您在《<strong>' . get_the_title($comment->comment_post_ID) . '</strong>》的评论：</p>
		</div>
		<div><style type="text/css">.one a{display:none}.one strong{color:#4489c2}</style>
			<div class="one" style="color:#100;background-color:#f9f9f9;border:1px solid #EEE;margin:1.5em 0 1em;overflow:auto;padding:10px">
			<strong>您</strong> 的评论原文是：' . trim(get_comment($parent_id)->comment_content) . '</div>
			<div class="one" style="color:#100;background-color:#f9f9f9;border:1px solid #EEE;margin:1em 0 1.5em 30px;overflow:auto;padding:10px">
			<strong>' . trim($comment->comment_author) . '</strong> 给您的回复：' . trim($comment->comment_content) . '</div>
			<p>您可以点击 <a href="' . htmlspecialchars(get_comment_link($parent_id)) . '">查看回复完整内容</a></p>
			<p><strong>温馨提示：本邮件由系统自动发送，请勿直接回复！</strong></p>
			<p>&copy; <strong><a href="' . get_option('home') . '" target="_blank">' . get_option('blogname') . '</a></strong>
			；欢迎 <a href="' . get_bloginfo('rss2_url') .'" target="_blank">订阅</a> 本站，欢迎再次光临！</p> 
		</div>';
		$from = "From: \"" . get_option('blogname') . "\" <$wp_email>";
		$headers = "$from\nContent-Type: text/html; charset=" . get_option('blog_charset') . "\n";
		wp_mail( $to, $subject, $message, $headers );
		//echo 'mail to ', $to, '<br/> ' , $subject, $message; // for testing
	}
}
add_action('comment_post', 'comment_mail_notify');

/* 自動加勾選欄 */
function add_checkbox() {
	echo '<p class="comment-form-field comment_mail"><input type="checkbox" name="comment_mail_notify" id="comment_mail_notify" value="comment_mail_notify" checked="checked" /><label for="comment_mail_notify">有人回复时邮件通知我</label></p>';
}
add_action('comment_form', 'add_checkbox');
// -- END ----------------------------------------

//评论作者链接新窗口打开
function my_get_comment_author_link() { //by zwwooooo
	$url    = get_comment_author_url( $comment_ID );
	$author = get_comment_author( $comment_ID );
	if ( empty( $url ) || 'http://' == $url )
		return $author;
	else
		return "<a target='_blank' href='$url' rel='external nofollow' class='url'>$author</a>";
}
add_filter('get_comment_author_link', 'my_get_comment_author_link');

// 评论回复
if ( ! function_exists( 'wwmm_comment' ) ) :
function wwmm_comment( $comment, $args, $depth ) {
	$GLOBALS['comment'] = $comment;
	switch ( $comment->comment_type ) :
		case '' :
?>
	<li <?php comment_class(); ?> id="li-comment-<?php comment_ID(); ?>">
		<div id="comment-<?php comment_ID(); ?>">
		<div class="comment-author">
			<?php echo get_avatar( $comment, 40 ); ?>
			<?php printf( __( '<cite class="fn">%s</cite>'), get_comment_author_link() ); ?>
		</div><!-- .comment-author .vcard -->
		<?php if ( $comment->comment_approved == '0' ) : ?>
			<em class="comment-awaiting-moderation"><?php _e( 'Your comment is awaiting moderation.' ); ?></em>
			<br />
		<?php endif; ?>

		<div class="comment-meta commentmetadata"><a href="<?php echo esc_url( get_comment_link( $comment->comment_ID ) ); ?>">
			<?php
				/* translators: 1: date, 2: time */
				printf( __( '%1$s at %2$s' ), get_comment_date(), get_comment_time() ); time_ago(); ?></a><?php edit_comment_link( __( 'Edit' ), ' ' );
			?>
		</div><!-- .comment-meta .commentmetadata -->

		<div class="comment-body"><?php comment_text(); ?></div>

		<div class="reply">
			<?php comment_reply_link( array_merge( $args, array( 'depth' => $depth, 'max_depth' => $args['max_depth'] ) ) ); ?>
		</div><!-- .reply -->
	</div><!-- #comment-##  -->

	<?php
			break;
		case 'pingback'  :
		case 'trackback' :
	?>
	<li class="post pingback">
		<p>广播信息：<?php comment_author_link(); ?><?php edit_comment_link( __( 'Edit' ), ' ' ); ?></p>
	<?php
			break;
	endswitch;
}
endif;
?>